import { useState, useImperativeHandle, Ref } from 'react';
import { Modal, message, Form, Input } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { changePassword } from 'api/user';
import md5 from 'js-md5';
import { useNavigate } from 'react-router-dom';

export interface PassModalProps {
	showModal: (params: any) => void;
}

interface Props {
	innerRef: Ref<PassModalProps | undefined>;
}

const PasswordModal = (props: Props) => {
	const navigator = useNavigate();
	const [isModalVisible, setIsModalVisible] = useState(false);

	useImperativeHandle(
		props.innerRef,
		(): PassModalProps => ({
			showModal,
		})
	);

	const showModal = (params: any) => {
		setIsModalVisible(true);
	};

	const handleCancel = () => {
		setIsModalVisible(false);
		form.resetFields();
	};

	const [form] = Form.useForm();
	async function onFinish(formdata: any) {
		let { surePassword, newPassWord, passWord } = formdata;
		form.resetFields();
		if (surePassword !== newPassWord) return message.error('两次输入的密码不一致');
		if (passWord === newPassWord) return message.error('与原密码一致');
		passWord = md5(passWord);
		newPassWord = md5(newPassWord);
		await changePassword({ passWord, newPassWord });
		message.success('修改密码成功 🎉🎉🎉');
		setIsModalVisible(false);
		navigator('/login');
	}
	return (
		<Modal
			title={<p className=' text-xl mb-4'>修改密码</p>}
			open={isModalVisible}
			onOk={form.submit}
			onCancel={handleCancel}
			destroyOnClose={true}>
			<Form
				form={form}
				name='basic'
				labelCol={{ span: 5 }}
				initialValues={{ remember: true }}
				onFinish={onFinish}
				size='large'
				autoComplete='off'>
				<Form.Item name='passWord' rules={[{ required: true, message: '请输入旧密码' }]}>
					<Input.Password autoComplete='new-passWord' placeholder='旧密码' prefix={<LockOutlined />} />
				</Form.Item>
				<Form.Item name='newPassWord' rules={[{ required: true, message: '请输入新密码' }]}>
					<Input.Password autoComplete='new-passWord' placeholder='新密码' prefix={<LockOutlined />} />
				</Form.Item>
				<Form.Item name='surePassword' rules={[{ required: true, message: '请再次输入新密码' }]}>
					<Input.Password autoComplete='new-passWord' placeholder='再次输入新密码' prefix={<LockOutlined />} />
				</Form.Item>
			</Form>
		</Modal>
	);
};
export default PasswordModal;
